import java.util.PriorityQueue;

//建立用于充当优先级队列元素的任务进程
class MyTask implements Comparable<MyTask> {
    public Runnable runnable;//要执行的任务
    public long time;//任务执行的时间

    public MyTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
}
/*创建一个定时器*/
public class MyTimer {
    private PriorityQueue<MyTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    //这是一个将进程放入优先级队列的方法
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            MyTask myTask = new MyTask(runnable,delay);
            queue.offer(myTask);
            locker.notify();
        }
    }
/*这个构造方法中的进程会判断优先级队列中的队首元素是否到达执行时间*/
    public MyTimer(){
        Thread t = new Thread(()->{
           while (true) {
               try {
                   synchronized (locker) {
                       while (queue.isEmpty()) {
                           locker.wait();
                       }
                       MyTask myTask = queue.peek();
                       long curTime = System.currentTimeMillis();
                       if (curTime >= myTask.time){
                           queue.poll();
                           myTask.runnable.run();
                       }else {
                           locker.wait(myTask.time - curTime);
                       }
                   }
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
           }
        });
        t.start();
    }
}
